package com.geek.bams.server;

import com.geek.bams.entity.Account;
import com.geek.bams.entity.CreditAccount;
import com.geek.bams.entity.LoanCreditAccount;
import com.geek.bams.entity.LoanSavingAccount;
import com.geek.bams.service.Bank;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 上帝视角面板 - 显示银行统计数据
 */
public class GodModePanel extends JFrame {
    
    private Bank bank;
    private ATMServer server;
    private JTextArea displayArea;
    private JLabel displayLabel;
    private CardLayout cardLayout;
    private JPanel cardPanel;
    
    // 当前选中的功能类型
    private String currentFunction = "";
    
    // 定时刷新定时器
    private javax.swing.Timer refreshTimer;
    
    public GodModePanel(ATMServer server) {
        this.bank = Bank.getInstance();
        this.server = server;
        initComponents();
        startAutoRefresh();
    }
    
    private void initComponents() {
        setTitle("排行榜");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        // 窗口关闭时停止定时器
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                stopAutoRefresh();
            }
        });
        setLocationRelativeTo(null);
        setResizable(true);
        
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(new Color(45, 45, 45)); // 深灰色背景
        
        // 顶部标题
        JLabel titleLabel = new JLabel("排行榜", SwingConstants.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setPreferredSize(new Dimension(0, 60));
        mainPanel.add(titleLabel, BorderLayout.NORTH);
        
        // 中间区域：左侧按钮 + 右侧显示区域
        JPanel centerPanel = new JPanel(new GridLayout(1, 2, 10, 10));
        centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 左侧按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
        buttonPanel.setBackground(new Color(45, 45, 45));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        // 创建按钮
        JButton totalBalanceButton = createButton("统计账户余额总数");
        totalBalanceButton.addActionListener(e -> {
            currentFunction = "balance";
            showTotalBalance();
        });
        
        JButton totalCeilingButton = createButton("统计账户透支额总数");
        totalCeilingButton.addActionListener(e -> {
            currentFunction = "ceiling";
            showTotalCeiling();
        });
        
        JButton totalLoanButton = createButton("统计账户贷款额总数");
        totalLoanButton.addActionListener(e -> {
            currentFunction = "loan";
            showTotalLoanAmount();
        });
        
        JButton rankButton = createButton("排行榜");
        rankButton.addActionListener(e -> {
            currentFunction = "rank";
            showRank();
        });
        
        JButton returnButton = createButton("返 回");
        returnButton.addActionListener(e -> {
            stopAutoRefresh();
            dispose();
        });
        
        // 添加按钮到面板
        buttonPanel.add(totalBalanceButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(totalCeilingButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(totalLoanButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(rankButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(returnButton);
        
        // 右侧显示区域
        JPanel displayPanel = new JPanel(new BorderLayout());
        displayPanel.setBackground(new Color(60, 60, 60));
        displayPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
        
        // 使用JTextArea显示多行内容（排行榜）
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        displayArea.setFont(new Font("Consolas", Font.PLAIN, 12));
        displayArea.setBackground(new Color(60, 60, 60));
        displayArea.setForeground(Color.WHITE);
        displayArea.setLineWrap(false); // 排行榜不需要自动换行
        displayArea.setWrapStyleWord(false);
        
        // 使用JLabel显示单行数字（统计数据）
        displayLabel = new JLabel("0.0", SwingConstants.CENTER);
        displayLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 32));
        displayLabel.setForeground(Color.WHITE);
        displayLabel.setVerticalAlignment(SwingConstants.CENTER);
        
        JScrollPane scrollPane = new JScrollPane(displayArea);
        scrollPane.setBorder(null);
        scrollPane.setBackground(new Color(60, 60, 60));
        
        // 使用CardLayout来切换显示
        cardLayout = new CardLayout();
        cardPanel = new JPanel(cardLayout);
        cardPanel.setBackground(new Color(60, 60, 60));
        cardPanel.add(displayLabel, "label");
        cardPanel.add(scrollPane, "area");
        
        displayPanel.add(cardPanel, BorderLayout.CENTER);
        
        // 默认显示排行榜
        currentFunction = "rank";
        showRank();
        
        centerPanel.add(buttonPanel);
        centerPanel.add(displayPanel);
        
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        
        add(mainPanel);
    }
    
    /**
     * 创建按钮
     */
    private JButton createButton(String text) {
        JButton button = new JButton(text);
        button.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 14));
        button.setForeground(Color.WHITE);
        button.setBackground(new Color(60, 60, 60));
        button.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
        button.setPreferredSize(new Dimension(200, 40));
        button.setMaximumSize(new Dimension(200, 40));
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        
        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(80, 80, 80));
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(60, 60, 60));
            }
        });
        
        return button;
    }
    
    /**
     * 启动自动刷新
     */
    private void startAutoRefresh() {
        if (refreshTimer != null) {
            refreshTimer.stop();
        }
        // 每2秒自动刷新一次
        refreshTimer = new javax.swing.Timer(2000, e -> {
            if (!currentFunction.isEmpty()) {
                refreshCurrentFunction();
            }
        });
        refreshTimer.start();
    }
    
    /**
     * 停止自动刷新
     */
    private void stopAutoRefresh() {
        if (refreshTimer != null) {
            refreshTimer.stop();
            refreshTimer = null;
        }
    }
    
    /**
     * 刷新当前功能
     */
    private void refreshCurrentFunction() {
        if (currentFunction.isEmpty()) {
            return;
        }
        
        switch (currentFunction) {
            case "balance":
                showTotalBalance();
                break;
            case "ceiling":
                showTotalCeiling();
                break;
            case "loan":
                showTotalLoanAmount();
                break;
            case "rank":
                showRank();
                break;
        }
    }
    
    /**
     * 获取在线用户账户列表
     */
    private List<Account> getOnlineAccounts() {
        if (server == null) {
            return new ArrayList<>();
        }
        return server.getOnlineAccounts();
    }
    
    /**
     * 显示账户余额总数（仅统计在线用户）
     */
    private void showTotalBalance() {
        try {
            List<Account> onlineAccounts = getOnlineAccounts();
            double totalBalance = 0.0;
            
            for (Account account : onlineAccounts) {
                if (account != null) {
                    totalBalance += account.getBalance();
                }
            }
            
            displayLabel.setText(String.format("%.2f", totalBalance));
            cardLayout.show(cardPanel, "label");
        } catch (Exception e) {
            displayLabel.setText("获取失败");
            cardLayout.show(cardPanel, "label");
            e.printStackTrace();
        }
    }
    
    /**
     * 显示账户透支额总数（仅统计在线用户）
     */
    private void showTotalCeiling() {
        try {
            List<Account> onlineAccounts = getOnlineAccounts();
            double totalCeiling = 0.0;
            
            for (Account account : onlineAccounts) {
                if (account != null && account instanceof CreditAccount) {
                    totalCeiling += ((CreditAccount) account).getCeiling();
                }
            }
            
            displayLabel.setText(String.format("%.2f", totalCeiling));
            cardLayout.show(cardPanel, "label");
        } catch (Exception e) {
            displayLabel.setText("获取失败");
            cardLayout.show(cardPanel, "label");
            e.printStackTrace();
        }
    }
    
    /**
     * 显示账户贷款额总数（仅统计在线用户）
     */
    private void showTotalLoanAmount() {
        try {
            List<Account> onlineAccounts = getOnlineAccounts();
            double totalLoan = 0.0;
            
            for (Account account : onlineAccounts) {
                if (account != null) {
                    if (account instanceof LoanSavingAccount) {
                        totalLoan += ((LoanSavingAccount) account).getLoanAmount();
                    } else if (account instanceof LoanCreditAccount) {
                        totalLoan += ((LoanCreditAccount) account).getLoanAmount();
                    }
                }
            }
            
            displayLabel.setText(String.format("%.2f", totalLoan));
            cardLayout.show(cardPanel, "label");
        } catch (Exception e) {
            displayLabel.setText("获取失败");
            cardLayout.show(cardPanel, "label");
            e.printStackTrace();
        }
    }
    
    /**
     * 显示排行榜（仅显示在线用户，按余额降序排列）
     */
    private void showRank() {
        try {
            List<Account> onlineAccounts = getOnlineAccounts();
            
            // 切换到显示区域
            cardLayout.show(cardPanel, "area");
            
            if (onlineAccounts == null || onlineAccounts.isEmpty()) {
                displayArea.setText("暂无在线用户\n\n请确保有用户已登录服务器");
                displayArea.setCaretPosition(0);
                return;
            }
            
            // 按余额降序排序
            onlineAccounts.sort(new Comparator<Account>() {
                @Override
                public int compare(Account a1, Account a2) {
                    return Double.compare(a2.getBalance(), a1.getBalance());
                }
            });
            
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("%-5s %-20s %-20s %-15s\n", 
                "Num", "ID", "Name", "money"));
            sb.append("─────────────────────────────────────────────────────────────\n");
            
            int rank = 1;
            for (Account account : onlineAccounts) {
                if (account != null) {
                    sb.append(String.format("%-5d %-20d %-20s %-15.2f\n", 
                        rank++, account.getId(), account.getName(), account.getBalance()));
                }
            }
            
            displayArea.setText(sb.toString());
            displayArea.setCaretPosition(0);
        } catch (Exception e) {
            displayArea.setText("获取排行榜失败：" + e.getMessage() + "\n\n错误详情：" + e.getClass().getName());
            displayArea.setCaretPosition(0);
            e.printStackTrace();
        }
    }
}

